package com.pactera.demo.security.filter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pactera.demo.common.util.RequestUtil;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY;
import static org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY;


/**
 * @author zhouchang
 * @since 2019/10/17 22:21
 */
public class JsonLoginPostProcessor implements LoginPostProcessor {

    private static ThreadLocal<String> passwordThreadLocal = new ThreadLocal<>();


    @Override
    public String obtainUsername(ServletRequest request) throws IOException {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request);
        String body = RequestUtil.obtainBody(requestWrapper);
        ObjectMapper mapper = new ObjectMapper();
        Map<String,String> map = mapper.readValue(body, new TypeReference<HashMap>() {});
        passwordThreadLocal.set(map.get(SPRING_SECURITY_FORM_PASSWORD_KEY));
        return map.get(SPRING_SECURITY_FORM_USERNAME_KEY);
    }

    @Override
    public String obtainPassword(ServletRequest request) {
        String password = passwordThreadLocal.get();
        passwordThreadLocal.remove();
        return password;
    }
}
